/**
 * 刘海屏检测工具
 * 检测当前设备是否为刘海屏/异形屏设备
 */

class NotchDetector {
  constructor() {
    this.isNotchDevice = false;
    this.safeAreaInsets = {
      top: 0,
      right: 0,
      bottom: 0,
      left: 0
    };
    this.deviceInfo = {
      userAgent: navigator.userAgent,
      screenWidth: window.screen.width,
      screenHeight: window.screen.height,
      windowWidth: window.innerWidth,
      windowHeight: window.innerHeight,
      devicePixelRatio: window.devicePixelRatio || 1
    };
    
    this.init();
  }

  init() {
    this.detectNotch();
    this.getSafeAreaInsets();
    this.detectDeviceModel();
  }

  /**
   * 检测是否为刘海屏设备
   */
  detectNotch() {
    // 方法1: 检测CSS环境变量
    if (this.checkCSSEnvironmentVariables()) {
      this.isNotchDevice = true;
      return;
    }

    // 方法2: 检测屏幕比例
    if (this.checkScreenRatio()) {
      this.isNotchDevice = true;
      return;
    }

    // 方法3: 检测已知设备型号
    if (this.checkKnownDevices()) {
      this.isNotchDevice = true;
      return;
    }

    // 方法4: 检测WebView特性
    if (this.checkWebViewFeatures()) {
      this.isNotchDevice = true;
      return;
    }
  }

  /**
   * 检测CSS环境变量（最可靠的方法）
   */
  checkCSSEnvironmentVariables() {
    try {
      // 创建临时元素测试CSS环境变量
      const testElement = document.createElement('div');
      testElement.style.position = 'fixed';
      testElement.style.top = '0';
      testElement.style.left = '0';
      testElement.style.width = '1px';
      testElement.style.height = '1px';
      testElement.style.visibility = 'hidden';
      testElement.style.paddingTop = 'env(safe-area-inset-top)';
      testElement.style.paddingRight = 'env(safe-area-inset-right)';
      testElement.style.paddingBottom = 'env(safe-area-inset-bottom)';
      testElement.style.paddingLeft = 'env(safe-area-inset-left)';
      
      document.body.appendChild(testElement);
      
      const computedStyle = window.getComputedStyle(testElement);
      const topInset = parseInt(computedStyle.paddingTop) || 0;
      const rightInset = parseInt(computedStyle.paddingRight) || 0;
      const bottomInset = parseInt(computedStyle.paddingBottom) || 0;
      const leftInset = parseInt(computedStyle.paddingLeft) || 0;
      
      document.body.removeChild(testElement);
      
      // 如果任何一个安全区域大于0，说明是刘海屏
      if (topInset > 0 || rightInset > 0 || bottomInset > 0 || leftInset > 0) {
        this.safeAreaInsets = {
          top: topInset,
          right: rightInset,
          bottom: bottomInset,
          left: leftInset
        };
        return true;
      }
    } catch (error) {
      console.warn('CSS环境变量检测失败:', error);
    }
    
    return false;
  }

  /**
   * 检测屏幕比例
   */
  checkScreenRatio() {
    const { screenWidth, screenHeight } = this.deviceInfo;
    const ratio = Math.max(screenWidth, screenHeight) / Math.min(screenWidth, screenHeight);
    
    // 刘海屏设备通常有更高的宽高比
    // iPhone X系列: ~2.17, 大部分Android刘海屏: >2.0
    return ratio > 2.0;
  }

  /**
   * 检测已知的刘海屏设备
   */
  checkKnownDevices() {
    const ua = this.deviceInfo.userAgent.toLowerCase();
    
    // iPhone X系列检测
    const iPhoneXModels = [
      'iphone x', 'iphone xs', 'iphone xs max', 'iphone xr',
      'iphone 11', 'iphone 11 pro', 'iphone 11 pro max',
      'iphone 12', 'iphone 12 mini', 'iphone 12 pro', 'iphone 12 pro max',
      'iphone 13', 'iphone 13 mini', 'iphone 13 pro', 'iphone 13 pro max',
      'iphone 14', 'iphone 14 plus', 'iphone 14 pro', 'iphone 14 pro max',
      'iphone 15', 'iphone 15 plus', 'iphone 15 pro', 'iphone 15 pro max'
    ];
    
    // Android刘海屏设备关键词
    const androidNotchKeywords = [
      'notch', 'cutout', 'punch', 'hole',
      'huawei p20', 'huawei p30', 'huawei mate 20', 'huawei mate 30',
      'xiaomi mi 8', 'xiaomi mi 9', 'xiaomi mi 10', 'xiaomi mi 11',
      'oppo find x', 'oppo r15', 'oppo r17',
      'vivo x21', 'vivo x23', 'vivo nex',
      'oneplus 6', 'oneplus 7', 'oneplus 8', 'oneplus 9'
    ];
    
    // 检测iPhone X系列
    for (const model of iPhoneXModels) {
      if (ua.includes(model)) {
        return true;
      }
    }
    
    // 检测Android刘海屏
    for (const keyword of androidNotchKeywords) {
      if (ua.includes(keyword)) {
        return true;
      }
    }
    
    return false;
  }

  /**
   * 检测WebView特性
   */
  checkWebViewFeatures() {
    // 检测是否在支持刘海屏的WebView中
    if (window.webkit && window.webkit.messageHandlers) {
      return true;
    }
    
    // 检测Android WebView
    if (window.Android && typeof window.Android.getNotchInfo === 'function') {
      return true;
    }
    
    return false;
  }

  /**
   * 获取安全区域边距
   */
  getSafeAreaInsets() {
    if (this.safeAreaInsets.top > 0) {
      return this.safeAreaInsets;
    }
    
    // 如果CSS检测失败，尝试其他方法
    try {
      // 检测状态栏高度（间接方法）
      const statusBarHeight = this.getStatusBarHeight();
      if (statusBarHeight > 24) { // 正常状态栏通常是24px
        this.safeAreaInsets.top = statusBarHeight;
      }
    } catch (error) {
      console.warn('获取安全区域失败:', error);
    }
    
    return this.safeAreaInsets;
  }

  /**
   * 获取状态栏高度
   */
  getStatusBarHeight() {
    // 在WebView中可能可以获取到状态栏高度
    if (window.StatusBar && window.StatusBar.height) {
      return window.StatusBar.height;
    }
    
    // 根据设备型号估算
    const { devicePixelRatio } = this.deviceInfo;
    const ua = this.deviceInfo.userAgent.toLowerCase();
    
    if (ua.includes('iphone')) {
      if (ua.includes('iphone x') || ua.includes('iphone 1')) {
        return 44 * devicePixelRatio; // iPhone X系列状态栏更高
      }
      return 20 * devicePixelRatio; // 传统iPhone
    }
    
    return 24 * devicePixelRatio; // Android默认
  }

  /**
   * 检测设备型号
   */
  detectDeviceModel() {
    const ua = this.deviceInfo.userAgent;
    
    // iPhone检测
    const iPhoneMatch = ua.match(/iPhone(\d+,\d+)/);
    if (iPhoneMatch) {
      this.deviceInfo.model = `iPhone ${iPhoneMatch[1]}`;
    }
    
    // Android检测
    const androidMatch = ua.match(/Android\s+([\d.]+)/);
    if (androidMatch) {
      this.deviceInfo.androidVersion = androidMatch[1];
    }
  }

  /**
   * 获取检测结果
   */
  getDetectionResult() {
    return {
      isNotchDevice: this.isNotchDevice,
      safeAreaInsets: this.safeAreaInsets,
      deviceInfo: this.deviceInfo,
      recommendations: this.getRecommendations()
    };
  }

  /**
   * 获取适配建议
   */
  getRecommendations() {
    if (!this.isNotchDevice) {
      return ['当前设备无需特殊适配'];
    }
    
    const recommendations = [
      '检测到刘海屏设备，建议进行以下适配：',
      '1. 使用 CSS env(safe-area-inset-*) 设置安全区域',
      '2. 确保重要内容不被刘海遮挡',
      '3. 适配横竖屏切换',
      '4. 测试不同设备的显示效果'
    ];
    
    if (this.safeAreaInsets.top > 0) {
      recommendations.push(`5. 顶部安全区域: ${this.safeAreaInsets.top}px`);
    }
    
    if (this.safeAreaInsets.bottom > 0) {
      recommendations.push(`6. 底部安全区域: ${this.safeAreaInsets.bottom}px`);
    }
    
    return recommendations;
  }

  /**
   * 实时监听设备方向变化
   */
  onOrientationChange(callback) {
    const handleOrientationChange = () => {
      setTimeout(() => {
        this.init(); // 重新检测
        callback(this.getDetectionResult());
      }, 100);
    };
    
    window.addEventListener('orientationchange', handleOrientationChange);
    window.addEventListener('resize', handleOrientationChange);
    
    return () => {
      window.removeEventListener('orientationchange', handleOrientationChange);
      window.removeEventListener('resize', handleOrientationChange);
    };
  }
}

// 创建全局实例
const notchDetector = new NotchDetector();

export default notchDetector;
export { NotchDetector };